﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EBA.Ex;

namespace EBA.Serialization
{
    class XmlSerializer : ISerializer
    {
        public XmlSerializer()
        {

        }



        public string Serialize<T>(T instance)
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, instance);
                return writer.ToString();
            }
        }

        public string SerializeObject(object instance)
        {
            if (instance == null)
            {
                return string.Empty;
            }
            var serializer = new System.Xml.Serialization.XmlSerializer(instance.GetType());

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, instance);
                return writer.ToString();
            }
        }

        public object DeserializeObject(Type type, string content)
        {

            if (content.HasValue())
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(type);

                using (TextReader reader = new StringReader(content))
                {
                    return serializer.Deserialize(reader);
                }
            }
            else
            {
                return null;
            }
        }

        public T Deserialize<T>(string content)
        {
            return (T)this.DeserializeObject(typeof(T), content);
        }
    }
}
